package com.vidmt.api.modules.sys;

import com.vidmt.api.modules.sys.Enums.AccType;
import com.vidmt.api.modules.sys.entity.User;
import com.vidmt.api.modules.sys.utils.VUtil;

public final class Acc {
	private static final String NUM_PATTERN = "^[1-9]\\d{0,19}$";

	private final AccType type;
	private final String value;

	public Acc(AccType type, String value) {
		if (type == AccType.uid && !value.matches(NUM_PATTERN)) {
			throw new IllegalArgumentException("非法的用户名类型:" + String.format("USER[%s/%s]", type, value));
		} else if (type == AccType.phone && !VUtil.isPhoneFmt(value)) {
			throw new IllegalArgumentException("非法的用户名类型:" + String.format("USER[%s/%s]", type, value));
		}
		this.type = type;
		this.value = value;
	}

	public Acc(String fullacc) {
		String[] arr = fullacc.split(":");
		if (arr.length == 1) {
			if (arr[0].matches(NUM_PATTERN)) {
				this.type = AccType.uid;
				this.value = arr[0];
			} else {
				throw new IllegalArgumentException("非法的用户名类型:" + fullacc);
			}
		} else if (arr.length == 2) {
			try {
				this.type = AccType.valueOf(arr[0]);
			} catch (Throwable e) {
				throw new IllegalArgumentException("非法的用户名类型:" + fullacc);
			}
			if (this.type == AccType.uid && !arr[1].matches(NUM_PATTERN)) {
				throw new IllegalArgumentException("非法的用户名类型:" + fullacc);
			} else if (this.type == AccType.phone && !VUtil.isPhoneFmt(arr[1])) {
				throw new IllegalArgumentException("非法的用户名类型:" + fullacc);
			}
			this.value = arr[1];
		} else {
			throw new IllegalArgumentException("非法的用户名类型:" + fullacc);
		}
	}

	public AccType type() {
		return type;
	}

	public String value() {
		return value;
	}

	public String asString() {
		return type + ":" + value;
	}

	@Override
	public String toString() {
		return String.format("USER[%s/%s]", type, value);
	}

	public User toUser() {
		User user = new User();
		switch (this.type()) {
		case uid:
			user.setId(Long.valueOf(this.value()));
			break;
		case name:
			user.setName(this.value());
			break;
		case email:
			user.setEmail(this.value());
			break;
		case phone:
			user.setPhone(this.value());
			break;
		}
		return user;
	}
}
